import math
from gettext import ngettext


from django.http import JsonResponse
from django.utils.encoding import force_str

from rest_framework import status
from rest_framework.exceptions import APIException


class Throttled(APIException):
    status_code = status.HTTP_429_TOO_MANY_REQUESTS
    default_detail = "ddddd"
    extra_detail_singular = ""
    extra_detail_plural = "哈哈哈哈哈{wait}"
    default_code = 'throttled'

    def __init__(self, wait=None, detail=None, code=None):
        if detail is None:
            detail = force_str(self.default_detail)
        if wait is not None:
            wait = math.ceil(wait)
            detail = ' '.join((
                detail,
                # force_str(ngettext(self.extra_detail_singular.format(wait=wait),
                #                    self.extra_detail_plural.format(wait=wait),
                #                    wait))))
                force_str(ngettext(self.extra_detail_singular.format(wait=wait),self.extra_detail_plural.format(wait=wait),wait))))
        self.wait = wait
        super().__init__(detail, code)


def server_error(request, *args, **kwargs):
    """
    Generic 500 error handler.
    """
    data = {
        'error': 'Server Error (500)'
    }
    return JsonResponse(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


def bad_request(request, exception, *args, **kwargs):
    """
    Generic 400 error handler.
    """
    data = {
        'error': 'Bad Request (400)'
    }
    return JsonResponse(data, status=status.HTTP_400_BAD_REQUEST)
